package flc.ast.activity;

import androidx.annotation.LayoutRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.davemorrissey.labs.subscaleview.ImageSource;
import com.stark.jigsaw.puzzle.PuzzleLayout;
import com.stark.jigsaw.puzzle.PuzzleUtils;
import com.stark.jigsaw.puzzle.adapter.PuzzleLayoutAdapter;
import com.stark.jigsaw.puzzle.template.slant.NumberSlantLayout;
import com.stark.jigsaw.puzzle.template.straight.NumberStraightLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.databinding.ActivityPuzzleBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.RxUtil;

public class PuzzleActivity extends BaseAc<ActivityPuzzleBinding> {

    public static List<String> listPath = new ArrayList<>();
    //    public static int defaultSel = 0;
    private List<Bitmap> mBmpList = new ArrayList<>();
    private PuzzleLayout puzzleLayout;
    protected boolean isPicTooLarge = false;//判断图片是否过大
    private Bitmap OriBitmap;//横竖图的bitmap
    private boolean isOri;//是否为长图拼接

    @Override
    protected int onCreate() {
        return R.layout.activity_puzzle;
    }

    @Override
    protected void initView() {
        mDataBinding.ivPuzzleBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.tvPuzzle.setOnClickListener(this);
        mDataBinding.tvOri.setOnClickListener(this);
        mDataBinding.ivOriVertical.setOnClickListener(this);
        mDataBinding.ivOriHorizontal.setOnClickListener(this);
        mDataBinding.ivOriVertical.setOnClickListener(this);
        mDataBinding.ivPuzzleSave.setOnClickListener(this);
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvPuzzle://拼图
                clearSelection();
                isOri = false;
                mDataBinding.ivPuzzle.setVisibility(View.VISIBLE);
                mDataBinding.rvPuzzleList.setVisibility(View.VISIBLE);
                mDataBinding.myPuzzleView.setVisibility(View.VISIBLE);
                break;
            case R.id.tvOri://长图拼接
                clearSelection();
                isOri = true;
                mDataBinding.ivOri.setVisibility(View.VISIBLE);
                mDataBinding.llOri.setVisibility(View.VISIBLE);
                mDataBinding.mySubImgView.setVisibility(View.VISIBLE);
                break;
            case R.id.ivOriVertical://竖图拼接
                mDataBinding.ivOriVertical.setImageResource(R.drawable.pt8);
                mDataBinding.ivOriHorizontal.setImageResource(R.drawable.pt9);
                doPinTu(true);
                break;
            case R.id.ivOriHorizontal://横图拼接
                mDataBinding.ivOriVertical.setImageResource(R.drawable.pt81);
                mDataBinding.ivOriHorizontal.setImageResource(R.drawable.pt91);
                doPinTu(false);
                break;
            case R.id.ivPuzzleSave://保存
                if (isOri) {
                    saveOriImg();
                } else {
                    savePuzzleImg();
                }
                break;
        }
    }

    @Override
    protected void initData() {
        //获取拼图样式
        mDataBinding.rvPuzzleList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        PuzzleLayoutAdapter adapter = new PuzzleLayoutAdapter(getPuzzleItemLayoutId());
        adapter.setListDatas(PuzzleUtils.getPuzzleLayouts(listPath.size()));
        adapter.setListener(puzzleLayout -> {
            int themeType = 0;
            int themeId = 0;
            if (puzzleLayout instanceof NumberSlantLayout) {
                themeType = 0;
                themeId = ((NumberSlantLayout) puzzleLayout).getTheme();
            } else if (puzzleLayout instanceof NumberStraightLayout) {
                themeType = 1;
                themeId = ((NumberStraightLayout) puzzleLayout).getTheme();
            }
            mDataBinding.myPuzzleView.setPuzzleLayout(PuzzleUtils.getPuzzleLayout(themeType, listPath.size(), themeId));
            mDataBinding.myPuzzleView.addPieces(mBmpList);
        });
        mDataBinding.rvPuzzleList.setAdapter(adapter);
        int type = 1;
//        if (listPath.size() == 2 || listPath.size() == 3) {
//            type = 0;
//        }
        puzzleLayout = PuzzleUtils.getPuzzleLayout(type, listPath.size(), 0);//默认选中的效果
        mDataBinding.myPuzzleView.setPuzzleLayout(puzzleLayout);

        //获取并设置图片拼图
        setPic();
        //设置图片
        doPinTu(true);
    }

    //保存自由拼接
    private void savePuzzleImg() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<Boolean>() {

                    @Override
                    public void doBackground(ObservableEmitter<Boolean> emitter) {
                        ImageUtils.save2Album(ImageUtils.view2Bitmap(mDataBinding.myPuzzleView), Bitmap.CompressFormat.PNG);
                        //保存到历史作品
                        String filePath = FileUtil.generateFilePath(Content.myEditWork, ".png");
                        ImageUtils.save(ImageUtils.view2Bitmap(mDataBinding.myPuzzleView), filePath, Bitmap.CompressFormat.PNG);
                        emitter.onNext(true);
                    }

                    @Override
                    public void accept(Boolean isSave) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_success);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    //保存长图拼接
    private void saveOriImg() {
        showDialog(getString(R.string.saving));
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RxUtil.create(new RxUtil.Callback<Boolean>() {

                    @Override
                    public void doBackground(ObservableEmitter<Boolean> emitter) {
                        if (OriBitmap != null) {
                            ImageUtils.save2Album(OriBitmap, Bitmap.CompressFormat.PNG);
                            //保存到历史作品
                            String filePath = FileUtil.generateFilePath(Content.myEditWork, ".png");
                            ImageUtils.save(OriBitmap, filePath, Bitmap.CompressFormat.PNG);
                        }
                        emitter.onNext(true);
                    }

                    @Override
                    public void accept(Boolean isSave) {
                        dismissDialog();
                        ToastUtils.showShort(R.string.save_success);
                        startActivity(HomeActivity.class);
                    }
                });
            }
        }, 1000);
    }

    //拼图样式颜色
    protected @LayoutRes
    int getPuzzleItemLayoutId() {
        return R.layout.item_jigsaw_puzzle_layout_light;
    }

    //获取并设置拼图
    private void setPic() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                Bitmap bitmap = null;
                int width = DensityUtil.getWith(mContext) / 2;
                int height = DensityUtil.getHeight(mContext) / 2;
                for (String path : listPath) {
                    bitmap = getScaleBitmap(path, width, height);
                    mBmpList.add(bitmap);
                }
                emitter.onNext(true);
            }

            @Override
            public void accept(Boolean obj) {
                dismissDialog();
                mDataBinding.myPuzzleView.post(new Runnable() {
                    @Override
                    public void run() {
                        mDataBinding.myPuzzleView.addPieces(mBmpList);
                    }
                });
            }
        });
    }

    private Bitmap getScaleBitmap(String path, int width, int height) {
        try {
            return Glide.with(this).asBitmap().load(path).submit(width, height).get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Bitmap.createScaledBitmap(BitmapFactory.decodeFile(path), width, height, true);
    }

    //设置图片横竖
    protected void doPinTu(final boolean vertical) {
        showDialog(getString(com.stark.common.res.R.string.handling));
        RxUtil.create(new RxUtil.Callback<Bitmap>() {
            @Override
            public void doBackground(ObservableEmitter<Bitmap> emitter) {
                isPicTooLarge = false;
                Bitmap bitmap1 = null;
                try {
                    bitmap1 = BitmapFactory.decodeFile(listPath.get(0));
                    bitmap1 = ImageUtils.rotate(bitmap1, ImageUtils.getRotateDegree(listPath.get(0)),
                            bitmap1.getWidth() / 2, bitmap1.getHeight() / 2, true);
                    for (int i = 1; i < listPath.size(); i++) {
                        Bitmap bitmap2 = BitmapFactory.decodeFile(listPath.get(i));
                        bitmap2 = ImageUtils.rotate(bitmap2, ImageUtils.getRotateDegree(listPath.get(i)),
                                bitmap2.getWidth() / 2, bitmap2.getHeight() / 2, true);
                        if (!vertical) {
                            bitmap1 = horizontalPintu(bitmap1, bitmap2);
                        } else {
                            bitmap1 = pintu(bitmap1, bitmap2);
                        }
                    }
                } catch (OutOfMemoryError e) {
                    //e.printStackTrace();
                    isPicTooLarge = true;
                }
                emitter.onNext(bitmap1);
            }

            @Override
            public void accept(Bitmap bitmap) {
                dismissDialog();
                if (isPicTooLarge) {
                    ToastUtils.showShort(R.string.pic_is_too_large);
                }
                if (bitmap != null) {
                    mDataBinding.mySubImgView.setImage(ImageSource.bitmap(bitmap));
                }
                //获取要保存的图片bitmap
                OriBitmap = bitmap;
            }
        });
    }

    //竖向
    private Bitmap pintu(Bitmap bitmap1, Bitmap bitmap2) {
        Bitmap ret;
        int width = bitmap1.getWidth();
        if (width > 1024) {
            int h1 = bitmap1.getHeight() * 1024 / bitmap1.getWidth();
            bitmap1 = ImageUtils.scale(bitmap1, 1024, h1, true);
            width = 1024;
        }
        if (bitmap2.getWidth() != width) {
            int h2 = bitmap2.getHeight() * width / bitmap2.getWidth();
            ret = Bitmap.createBitmap(width, bitmap1.getHeight() + h2, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(ret);
            Bitmap newSizeBitmap2 = ImageUtils.scale(bitmap2, width, h2, true);
            canvas.drawBitmap(bitmap1, 0, 0, null);
            canvas.drawBitmap(newSizeBitmap2, 0, bitmap1.getHeight(), null);
        } else {
            ret = Bitmap.createBitmap(width, bitmap1.getHeight() + bitmap2.getHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(ret);
            canvas.drawBitmap(bitmap1, 0, 0, null);
            canvas.drawBitmap(bitmap2, 0, bitmap1.getHeight(), null);
        }
        return ret;
    }

    //横向
    private Bitmap horizontalPintu(Bitmap bitmap1, Bitmap bitmap2) {
        Bitmap ret;
        int height = bitmap1.getHeight();
        if (height > 1024) {
            int w1 = bitmap1.getWidth() * 1024 / bitmap1.getHeight();
            bitmap1 = ImageUtils.scale(bitmap1, w1, 1024, true);
            height = 1024;
        }
        if (bitmap2.getHeight() != height) {
            int w2 = bitmap2.getWidth() * height / bitmap2.getHeight();
            ret = Bitmap.createBitmap(bitmap1.getWidth() + w2, height, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(ret);
            Bitmap newSizeBitmap2 = ImageUtils.scale(bitmap2, w2, height, true);
            canvas.drawBitmap(bitmap1, 0, 0, null);
            canvas.drawBitmap(newSizeBitmap2, bitmap1.getWidth(), 0, null);
        } else {
            ret = Bitmap.createBitmap(height, bitmap1.getWidth() + bitmap2.getWidth(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(ret);
            canvas.drawBitmap(bitmap1, 0, 0, null);
            canvas.drawBitmap(bitmap2, bitmap1.getWidth(), 0, null);
        }
        return ret;
    }

    private void clearSelection() {
        mDataBinding.ivPuzzle.setVisibility(View.INVISIBLE);
        mDataBinding.ivOri.setVisibility(View.INVISIBLE);
        mDataBinding.rvPuzzleList.setVisibility(View.GONE);
        mDataBinding.llOri.setVisibility(View.GONE);
        mDataBinding.myPuzzleView.setVisibility(View.GONE);
        mDataBinding.mySubImgView.setVisibility(View.GONE);
    }

}